package top.jfunc.common.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

/**
 * 可以同类型的值一起保存多个
 * @param <T> 内存值
 */
public class MapMemoryRefresher<T> {
    private final Map<String, MemoryRefresher<T>> memoryRefresherMap;

    public MapMemoryRefresher() {
        this.memoryRefresherMap = new HashMap<>();
    }

    public MapMemoryRefresher(Map<String, MemoryRefresher<T>> memoryRefresherMap) {
        this.memoryRefresherMap = memoryRefresherMap;
    }

    public MapMemoryRefresher<T> put(String key, Supplier<T> dataGetter){
        return this.put(key, new MemoryRefresher<>(dataGetter));
    }
    public MapMemoryRefresher<T> put(String key, Supplier<T> dataGetter, long refreshTimeout){
        return this.put(key, new MemoryRefresher<>(dataGetter, refreshTimeout));
    }
    public MapMemoryRefresher<T> put(String key, MemoryRefresher<T> memoryRefresher){
        memoryRefresherMap.put(key, memoryRefresher);
        return this;
    }

    /**
     * key必须存在，否则抛出NPE
     */
    public T get(String key){
        if(!containsKey(key)){
            throw new IllegalArgumentException("[" + key + "]未初始化");
        }
        return memoryRefresherMap.get(key).get();
    }

    /**
     * key不存在则返回默认值
     */
    public T getOrDefault(String key, T defaultValue){
        if(!containsKey(key)){
            return defaultValue;
        }
        try {
            //实际获取过程中抛异常了也返回默认值
            return memoryRefresherMap.get(key).get();
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * 检查是否包含某个key
     */
    public boolean containsKey(String key){
        return memoryRefresherMap.containsKey(key);
    }

}
